//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from "react";
import type { TagInfo } from "@/api/roadmap_admin";
import { add_tag, modify_tag } from "@/api/roadmap_admin";
import { Form, Input, message, Modal } from "antd";
import { get_admin_session } from "@/api/admin_auth";
import { request } from "@/utils/request";


export interface EditTagModalProps {
    tagInfo?: TagInfo;
    onCancel: () => void;
    onOk: () => void;
}

const EditTagModal = (props: EditTagModalProps) => {
    const [tag, setTag] = useState(props.tagInfo?.tag ?? "");
    const [name, setName] = useState(props.tagInfo?.name ?? "");

    const addTag = async () => {
        const sessionId = await get_admin_session();
        try {
            await request(add_tag({
                session_id: sessionId,
                tag: tag,
                name: name,
            }));
            message.info("增加成功");
            props.onOk();
        } catch (e) {
            console.log(e);
            message.error("渠道ID冲突");
        }
    };

    const modifyTag = async () => {
        const sessionId = await get_admin_session();
        await request(modify_tag({
            session_id: sessionId,
            tag: tag,
            name: name,
        }));
        message.info("修改成功");
        props.onOk();
    };

    return (
        <Modal open title={props.tagInfo == undefined ? "增加渠道" : "修改渠道"} mask={false}
            okText={props.tagInfo == undefined ? "增加" : "修改"} okButtonProps={{ disabled: tag == "" || name == "" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.tagInfo == undefined) {
                    addTag();
                } else {
                    modifyTag();
                }
            }}>
            <Form labelCol={{ span: 3 }}>
                {props.tagInfo == undefined && (
                    <Form.Item label="渠道ID">
                        <Input value={tag} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setTag(e.target.value.trim());
                        }} />
                    </Form.Item>
                )}
                <Form.Item label="渠道名称">
                    <Input value={name} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setName(e.target.value.trim());
                    }} />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default EditTagModal;